<template>
	<view class="mainBox">
		<u-mask :show="showMask" @click="showMask = false" :zoom="false">
				<view class="pa" :style="{top:heightMask+'px',right:'50rpx'}">
					<image src="https://zhaimeibianli.oss-cn-hangzhou.aliyuncs.com/house/2024/07/26/24d369a4d07c4cecae92a4bcd45f75ca.png" style="width: 650rpx;height: 803rpx;"></image>
				</view>
			</u-mask>
		<u-navbar z-index="9999" :border-bottom="false" :is-back="false"
			:background="scrollTop > 45 ? backgroundScroll : background">
			<view class="df aic" :style="{'opacity' : (100 - scrollTop) / 100}">
				<view class="address df aic  mr30 ml30">
					<nmr-icon name="dingwei-3" color="#fff" size="30" class="mr10"></nmr-icon>
					<view class="fs26 textOver df aic" style="width: 166rpx;" v-if="token" @click="addressChoose">
						<view class="u-line-1" style="max-width: 135rpx;">
							{{addressInfo&&addressInfo.name||'请选择地址'}}
						</view>
						<nmr-icon size="24" name="xiangyou1" color="#fff"></nmr-icon>
					</view>
					<view class=" textOver" style="width: 220rpx;" @click="showLogin" v-else>
						未登录
						<nmr-icon size="24" name="xiangyou1" color="#fff"></nmr-icon>
					</view>
				</view>
				<text class="cf fs36">{{app_name}}</text>
			</view>
		</u-navbar>
		<view class=""
			style="position: absolute;width:750rpx;z-index: -1;height: 540rpx;     background: linear-gradient(180deg, #48A147, #71C570 200rpx,#eeeeee  500rpx); top:0;">
		</view>
		<view class="m30 searchBox" :style="{'top': menuButtonInfo.top + 'px'}">
			<view class="df aic">
				<nmr-icon @click="handlemyCoupon" class="mr20" name="a-9" size="50" islinear></nmr-icon>
				<u-search height="58" u-placeholder-class="placeholder-class" @click="handleToSearch" disabled style="width: 100%;" search-icon-color="#999"
					:show-action="false" bg-color="#e0f1e0" shape="round" placeholder="集采货品,宅美批发商城帮您忙,实惠更省心"
					v-model="keyword"></u-search>
				<nmr-icon @click="handleMsg" class="ml10" name="a-tongzhi-21" size="39" color="#fff"></nmr-icon>
				<view :style="{minWidth:searchSpaceWidth+'rpx'}"></view>
			</view>
		</view>

		<view class="m30" style="position: relative;z-index: 10;margin-bottom: 0;">

			<scroll-view scroll-x="true" class="" style="width: 700rpx;">
				<view class="df aic ">
					<view @click="toSearch(item.keyword)" style="min-width: 120rpx;padding: 5rpx 10rpx;"
						class="tac c9 fs22 mr16 bcE3f3e3 bdr20" v-for="(item,index) in bHeatKeywords" :key="index">
						{{item.keyword}}
					</view>
				</view>
			</scroll-view>
			<ModalMsg v-model="showLocaltion" confirmName="前往定位" @confirm="chooseLocation" :showCancel="false">
				<view class="address-desc mt30 fs26 c3 u-text-center">
					您当前暂未定位，请定位后使用服务
				</view>
			</ModalMsg>
			<view class="mt30 tac" v-if="bannerList.length">
				<u-swiper @click='clickBanner' :list="bannerList" height="690"></u-swiper>
			</view>
			<view class="mt30 bgcf bdr20" v-else>
				<view v-if="subjectList.length==0" class="df aic jcc"
					style="flex-direction: column;width: 100%; " >
					<image src="@/static/empty/store-empty.png" style="width: 320rpx;margin-top: 30rpx;height: 270rpx;" mode="widthFix"></image>
				</view>
				<swiper v-else indicator-color="#a3d0a3" indicator-active-color="#48A147" style="height: 400rpx;"
					class="swiper" circular :indicator-dots="true" :autoplay="false">
					<swiper-item v-for="(sub,subIndex) in subjectList" :key="subIndex">
						<view class="p24 bdr20" style="padding-bottom: 0;">
							<view class="df aic  w100" style="flex-wrap: wrap;">
								<view @click="clickSubject(item)" class="mt20 tac w20" v-for="(item,index) in sub"
									:key="index">
									<view style="margin: 0 auto;width: 100rpx;">
										<u-image width="100" height="100" :src="item.icon" borderRadius="50%"></u-image>
									</view>
									<view class="fs26 c3 u-line-1 u-text-center mt10">
										{{item.subjectName||''}}
									</view>
								</view>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<PriceContainer v-if="todayInfoData.length" :list="todayInfoData"></PriceContainer>
			<DailySale v-if="activityGoodsList.length" :list="activityGoodsList"></DailySale>
			<view class="bgcf bdr20  mt20 ">
				<template v-if="themeList.length">
					<view class="df aic jcsb p20">
						<image style="width: 148rpx;height: 53rpx;" src="../../static/index/scene.png" mode="widthFix">
						</image>
						<view class="themeLabel cf pl14 pr14 fs22">
							必备食材，样样都有哟~
						</view>
					</view>
					<view v-if="!themeList.length" class="df aic jcc"
						style="flex-direction: column;width: 100%; " >
						<image src="@/static/empty/content-empty.png" style="width: 320rpx;margin-top: 30rpx;height: 270rpx;" mode="widthFix"></image>
					</view>
					<view class="df aic fww jcsb  p20" style="padding-top: 0;">
						<image class="mr10 " @click="clickTheme(item)" v-for="(item,index) in themeList" :key="index"
							style="width: 315rpx;height: 162rpx;border-radius: 5rpx;" :src="item.bannerImage" mode="aspectFill"></image>
					</view>
				</template>
				<u-sticky @fixed="fixed" :offset-top="offsetTop">
					<view class="pr bgcf" style="padding: 20rpx 34rpx;" >
						<view class="df aic jcsb  pr20 pl20 " >
							<view class="tac pr"  v-for="(item,index) in hostTagList" :key="index"
								@click="classClick(index)">
								<view class="c3 fs26 textFamily pr" style="z-index: 2;" :class="index == classIndex ? 'c48A147' : ''">
									{{item.dictLabel}}
								</view>
								<view class="fs22 c6" :class="index == classIndex ? 'c48A147' : ''">
									{{item.remark}}
								</view>
								<image class="hotSalesStyle" :src="item.image" style="width: 32rpx;height: 32rpx;">
								</image>
							</view>
						</view>
						<image
							:class="classIndex == 0 ? 'leftOne' :classIndex == 1 ? 'leftTwo' : classIndex == 2 ? 'leftThree' : 'leftFour'"
							class="productActive" src="../../static/index/xiaolianxuanzhong.png"
							style="width: 36rpx;height: 12rpx;" mode=""></image>
					</view>
				</u-sticky>
			</view>
		</view>
		<view class="p30" style="padding-top: 0;">
			<view class="pr mt30" :style="{height: loginHeight+'px'}" v-if="logingGoods">
				<ourLoading :active="logingGoods" translateY="50" color="#48A147" background-color="white" size="4">
				</ourLoading>
			</view>
			<template v-else>
				<view v-if="flowList.length">
					<goodsList @changeCarList="changeCarList" :goodsCarList="goodsCarList" @changeSku="changeSku"
						ref="goodsList" @handleLogin="showLogin" :flowList="flowList"></goodsList>
					<u-loadmore bg-color="rgb(240, 240, 240)" margin-top="20" :status="loadStatus"
						:load-text="loadText"></u-loadmore>
				</view>
				<view v-else class="df aic jcc bgfff mt30" style="flex-direction: column;width: 100%;height: 400rpx; ">
					<image src="@/static/empty/content-empty.png" style="width: 300rpx;height: 156rpx;" mode="widthFix">
					</image>
					<view class="c9 fs28 ">
						暂无商品
					</view>
				</view>
			</template>
		</view>
		<LoginPopup @loginSuccess="loginSuccess" ref="LoginPopup"></LoginPopup>
		<newUserPopup  v-model="_newUSerCoupon.isNewMemberCoupon"></newUserPopup>
	</view>
</template>

<script>
	import ourLoading from '@/components/our-loading/our-loading.vue'
	import DailySale from './components/DailySale.vue'
	import PriceContainer from './components/PriceContainer.vue'
	import newUserPopup from './components/newUserPopup.vue'
	import {
		platformGoodsList
	} from '@/api/goods.js'
	import scrollBg from '@/static/index/scrollBg.png'
	import goodsList from '@/components/goodsList/goodsList.vue'
	import ModalMsg from '@/components/ModalMsg.vue'
	import {
		bPlatformGroupSelectList,
		queryTopBSubjectList
	} from '@/api/goods.js'
	import {
		bannerCode,
		bHeatKeywordsList,
		datatype
	} from '@/api/common.js'
import {appletListactivityGoods}from '@/other/api/activityGoods.js'
import {todayInfo} from '@/api/home.js'
	export default {
		components: {
			goodsList,
			ourLoading,
			ModalMsg,
			DailySale,
			PriceContainer,
			newUserPopup
		},
		data() {
			return {
				showCoupon:true,
				token: uni.getStorageSync('token'),
				app_name: this.APPTITLE,
				topHeight: '0',
				background: {
					backgroundColor: 'transparent',
				},
				backgroundScroll: {
					background: `url(${scrollBg}) no-repeat`,
					// 还可以设置背景图size属性
					backgroundSize: 'cover',
				},
				classIndex: 0,
				keyword: '',
				flowList: [],
				scrollTop: 0,
				menuButtonInfo: {},
				addressInfo: {
					address: '',
					longitude: '',
					latitude: '',
					name: ''
				},
				hostTagList: [], //热门标签
				themeList: [], //主题
				bannerList: [],
				bHeatKeywords: [],
				subjectList: [],
				loadStatus: 'loadmore',
				pageNum: 1,
				pageSize: 40,
				loadText: {
					loadmore: '轻轻上拉',
					loading: '努力加载中',
					nomore: '没有更多了'
				},
				logingGoods: true,
				goodsCarList: [],
				offsetTop:0,
				showMask:false,
				heightMask:0,
				loginHeight:1000,
				showLocaltion:false,
				activityGoodsList:[],
				todayInfoData:[]
			}
		},
		computed: {
			searchSpaceWidth() {
				let w =  97/(uni.upx2px(100)/100)+16.2
				if (this.scrollTop < 46) {
					console.log(this.scrollTop)
					return w/46*Number(this.scrollTop) 
				} else {
					return 97/(uni.upx2px(100)/100)+16.2
				}
			}
		},
		onLoad() {
			if(!uni.getStorageSync('showMask')){
				this.showMask = true
				uni.setStorageSync('showMask',true)
			}
			console.log('--')
			this.goodsCarList = uni.getStorageSync('CARGOODLIST')||[]
			if(!this.TOKEN){
				uni.removeTabBarBadge({
					index: 3
				})
			}else{
				let num = this.$common.clacCount(this.goodsCarList)
				if (num == 0) {
					uni.removeTabBarBadge({
						index: 3
					})
				} else {
					uni.setTabBarBadge({
						index: 3,
						text: num
					})
				}
			}
			
			this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			this.getKey()
			this.bannerCode()
			this.queryTopBSubjectList()
			this.bPlatformGroupSelectList(1)
			
			let that = this
			uni.getSystemInfo({
				success: function(res) {
					console.log(res)
					// #ifdef MP-WEIXIN
					that.topHeight = res.statusBarHeight < 21 ? '-32px' : res.statusBarHeight < 31 ? '-14px' :
						'0'

					console.log(that.topHeight)
					// #endif


				}
			});
			// 校验计算本地地址还是默认地址
		},
		onShow() {
			this.todayInfo()
			this.appletListactivityGoods()
			this.goodsCarList = uni.getStorageSync('CARGOODLIST')||[]
			let num = this.$common.clacCount(this.goodsCarList)
			if(num==0){
				uni.removeTabBarBadge({index:3})
			}else{
				uni.setTabBarBadge({
				  index: 3,
				  text: num
				})
			}
			this.$nextTick(() => {
				let pages = getCurrentPages()
				if (pages.length >= 1) {
					let prevpage = pages[0].__displayReporter.showReferpagepath
					if (prevpage !== 'pages/goods/detail.html') {
						this.logingGoods = true
						this.init()
						this.datatype()
						this.loginSuccess()
						this.clacGoodsSet()
					}
				}
			});
			
		},
		onHide() {
			this.$refs.goodsList.showSku = false
		},
		onUnload() {
			this.$refs.goodsList.showSku = false
		},
		onPageScroll: function(e) { //nvue暂不支持滚动监听，可用bindingx代替
			this.scrollTop = e.scrollTop
		},
		onReachBottom() {
			if(!this.hostTagList.length)return
			this.addRandomData();
		},
		mounted() {
			this.offsetTop  = 0
			let that = this
			uni.getSystemInfo({
				success: function(res) {
					that.offsetTop = ((res.platform == 'ios' ? 44 : 48) + res.statusBarHeight)/(uni.upx2px(100)/100); 
					that.heightMask = (res.platform == 'ios' ? 44 : 48) + res.statusBarHeight
					that.loginHeight = res.windowHeight-(res.platform == 'ios' ? 44 : 48) - res.statusBarHeight-uni.upx2px(71*2)
					console.log(that.loginHeight,'71',uni.upx2px(71*2),res.screenWidth)
				}
			});
		},
		onShareAppMessage(res) {
			return {
				title: this.APPSHARE.title,
				path: `/pages/index/index`,
				imageUrl: this.APPSHARE.imageUrl
			}
		},
		
		onShareTimeline() {
			return {
				title: this.APPSHARE.title,
				path: `/pages/index/index`,
				imageUrl: this.APPSHARE.imageUrl
			}
		},
		methods: {
			todayInfo(){
				todayInfo().then(res =>{
					if(res.code==200){
						this.todayInfoData = res.data
						console.log(this.todayInfoData)
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							mask:true
						})
					}
				})
			},
			appletListactivityGoods(){
				appletListactivityGoods().then(res =>{
					if(res.code==200){
						this.activityGoodsList = res.data
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							mask:true
						})
					}
				})
			},
			chooseLocation() {
				uni.navigateTo({
					url: '/pages/addressLocation'
				})
			},
			clickSubject(e) {
				uni.setStorage({
					key: "firstCateId",
					data: e.subjectId,
					success: function() {
						uni.switchTab({
							url: "/pages/class/index"
						})
					},
					fail: function() {}
				})
			},
			changeCarList(e) {
				this.goodsCarList = e
				uni.setStorageSync('CARGOODLIST',this.goodsCarList)
				let num = this.$common.clacCount(e)
				if(num==0){
					uni.removeTabBarBadge({index:3})
				}else{
					uni.setTabBarBadge({
					  index: 3,
					  text: num
					})
				}
			},
			// 与购物车无关 需要更新goodslist
			changeSku(e) {
				let goodsCarList = this.flowList||[]
				let index = goodsCarList.findIndex(i => i.platformGoodsId == e.platformGoodsId)
				if (index == -1) {
					goodsCarList.unshift(e)
				} else {
					if (e.purNum == 0) { //删除操作
						goodsCarList.splice(index, 1)
					} else {
						goodsCarList[index] = e
					}
				}
				this.flowList = goodsCarList
			},
			toSearch(e) {
				uni.navigateTo({
					url: '/pages/search/result?keyWord=' + e
				})
			},
			getKey() {
				return bHeatKeywordsList().then(res => {
					if (res.code == 200) {
						this.bHeatKeywords = res.data
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			},
			bannerCode() {
				return bannerCode({
					bannerCode: 'wx_home_b'
				}).then(res => {
					this.bannerList = res.data
				})
			},

			datatype() {
				return datatype('b_goods_label').then(res => {
					if (res.code == 200) {
						this.hostTagList = res.data
						this.classIndex = 0
						this.addRandomData()
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			},
			bPlatformGroupSelectList(groupType) {
				return bPlatformGroupSelectList({
					groupType: groupType
				}).then(res => {
					if (res.code == 200) {
						this.themeList = res.data
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			},
			clickBanner(e) {
				if(!this.TOKEN){
					this.showLogin()
					return
				}
				if(!this.LOCATION.areaId){
					this.showLocaltion = true
					return
				}
				this.$common.advJump(this.bannerList[e])
			},
			clickTheme(item) {
				let info =encodeURIComponent(JSON.stringify(item))
				uni.navigateTo({
					url: '/pages/class/scene?info='+info
				})
			},
			queryTopBSubjectList(groupType) {
				return queryTopBSubjectList({
					level: 1,
					isShowB: 0
				}).then(res => {
					this.subjectList = this.scliceData(res, 10)
					if (res.code == 200) {} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				})
			},
			handleMsg() {
				uni.navigateTo({
					url: '/pages/my/msgRecord/index'
				})
			},
			handlemyCoupon() {
				uni.navigateTo({
					url: '/pages/my/coupon/myCoupon'
				})
			},
			
			// 首页 如果登录后 需要获取 缓存中的地址 没有则 获取 默认地址，如果无默认地址 去跳转地址选择页面
			getDefault() {
				if (!uni.getStorageSync('token')) return
				if (this.LOCATION.name) { //缓存中有地址
					this.addressInfo = this.LOCATION
				}
			},
			// 默认地址  

			loginSuccess() {
				this.token = uni.getStorageSync('token')
				this.getDefault()

			},
			handleToSearch() {
				uni.navigateTo({
					url: '/pages/search/index'
				})
			},
			// 展示登录弹窗
			showLogin() {
				this.$refs.LoginPopup.checkLogin()
			},
			init() {
				this.loadStatus = 'loadmore'
				this.pageNum = 1
				this.pageSize = 40
				this.flowList = []
			},
			classClick(index) {
				if (this.classIndex == index) return
				this.classIndex = index
				this.logingGoods = true
				this.init()
				this.addRandomData()
			},
			addressChoose() {
				uni.navigateTo({
					url: '/pages/addressLocation'
				})
			},
			// 数组3位截取
			scliceData(data, num) {
				// data	数组
				// 	num	截取长度
				if (data.length === 0) return;
				let arr = [];
				const arrLength = Math.ceil(data.length / num);
				for (let i = 0; i < arrLength; i++) {
					const itemData = data.slice(i * num, i * num + num);
					arr.push(itemData);
				}
				// console.log(arr);
				return arr;
			},
			clacGoods(list) {
				return new Promise((resolve, reject) => {
					list.forEach(e => {
						e.platformGoodsSpecMix.forEach(mix => {
							let info = this.goodsCarList.find(_e => _e.platformGoodsSpecMixId ===
								mix
								.platformGoodsSpecMixId)
							if (info) {
								this.$set(mix, 'purNum', info.purNum)
								this.$set(mix, 'checkFlag', true)
							} else {
								this.$set(mix, 'purNum', 0)
								this.$set(mix, 'checkFlag', true)
							}
						})

					})
					resolve(list)
				})
			},
			async clacGoodsSet() {
				let list = await this.clacGoods(this.flowList)
				this.flowList = list
				this.$forceUpdate()
				console.log(this.flowList,'flowList')
			},

			addRandomData() {
				if (this.loadStatus == 'nomore' || this.loadStatus == 'loading') return
				this.loadStatus = 'loading'
				platformGoodsList({
					goodsLabel: this.hostTagList[this.classIndex].dictValue,
					pageNum: this.pageNum,
					pageSize: this.pageSize,
					flag:'normal'
				}).then(async res => {
					if (res.code == 200) {
						let list = await this.clacGoods(res.rows)
						// res.rows.forEach(e => {
						// 	e.platformGoodsSpecMix.forEach(mix =>{
						// 		let info = this.CARGOODLIST.find(_e => _e.platformGoodsSpecMixId === mix
						// 			.platformGoodsSpecMixId)
						// 		if (info) {
						// 			this.$set(mix,'purNum',info.purNum)
						// 			this.$set(mix,'checkFlag',true)
						// 		}else{
						// 			this.$set(mix,'purNum',0)
						// 			this.$set(mix,'checkFlag',true)
						// 		}
						// 	})

						// })
						this.flowList.push(...list)
						this.pageNum = ++this.pageNum;
						if (res.rows.length < this.pageSize) {
							this.loadStatus = 'nomore' //不用加载下一页
						} else {
							this.loadStatus = 'loadmore' //不用加载下一页
						}
						this.logingGoods = false
					} else {
						this.logingGoods = false
						uni.showToast({
							title: res.msg,
							icon: 'none',
							mask: true
						})
					}
				}).catch(e =>{
					this.logingGoods = false
				})
			},
		}
	}
</script>
<style>
	.u-placeholder-class{
		font-size: 24rpx;
	}
</style>
<style scoped>
	.rect {
		width: 120px;
		height: 120px;
		background-color: #fff;
	}
	.mainBox {
		width: 100;
		padding: 0;
	}

	.address {
		opacity: 1;
		color: #fff;
	}

	.search {
		opacity: 1;
	}

	.bcE3f3e3 {
		background: #e3f3e3;
	}

	.themeLabel {
		background: linear-gradient(90deg, #48A147 0%, #8AE38A 100%);
		border-radius: 19rpx 0rpx 19rpx 0rpx;
		padding: 5rpx 20rpx 5rpx 20rpx;
		opacity: 1;
	}

	.hotSalesStyle {
		position: absolute;
		top: -4rpx;
		left: -21rpx;
		z-index: 1;
	}

	.productActive {
		transition: all .5s;
	}

	.leftOne {
		margin-left: 54rpx;
	}

	.leftTwo {
		margin-left: 210rpx;
	}

	.leftThree {
		margin-left: 370rpx;
	}

	.leftFour {
		margin-left: 536rpx;
	}

	.c48A147 {
		color: #48A147;
	}

	.textFamily {
		font-family: PingFangSC-Semibold, PingFangSC-Semibold;
		font-weight: 600;

	}

	.searchBox {
		position: sticky;
		z-index: 9999;
		margin-top: 0;

	}
</style>